import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import progress from '@bassist/progress'
import constantRoutes from './routes'
import { APP_NAME } from '@/constants'
import { useMessageStore, usePermissionStore } from '@/stores'


let modulesCom = import.meta.glob('../components/head/*.vue')

let modulesView = import.meta.glob('../views/*/*.vue')
import { ElMessage } from 'element-plus'
import { sleep } from '@bassist/utils'

progress.configure({ showSpinner: false })
progress.setColor('var(--c-brand)')

const router = createRouter({
  // history: createWebHistory(import.meta.env.BASE_URL),
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes:constantRoutes,
  scrollBehavior: (to, from, savedPosition) => {
    return savedPosition ? savedPosition : { top: 0, left: 0 }
  },
})

router.beforeEach((to, from) => {
  let message = localStorage.getItem("message")
  // JSON message=JSON.parse(localStorage.getItem("message")?.toString);
  let loginStatus = JSON.parse(message || '{}').loginStatus
  let routerInit = JSON.parse(message || '{}').loginStatus
  console.log("message:", message,routerInit)
  console.log("to:", to)
  // if (to.path != "/login" && !loginStatus) {
  //   ElMessage({
  //     message: '请先登录'
  //     , type: "error"
  //   })
  //   router.push("/login")
  // }
  progress.start()
  //===================处理动态路由
  if(!localStorage.getItem("isSetRouter")){
    usePermissionStore().initMenu(router)
    console.log("-----setRouter")
  }else{
    console.log("---router")
  }
  
//  if(i==0){

  // router.addRoute({
  //   // name: 'user',
  //   path: '/user',
  //   meta: {
  //     requiresAuth: true,
  //     title: 'user',
  //   },
  //   component:  modulesCom[('../components/head/LayoutMain.vue')],
  //   children: [{ path: '/user',
  //    component: modulesView[('../views/user/index.vue')]
  //    }],
  // })
  // 下面这个可以
  // router.addRoute({
  //   path: "/user",
  //   // component: LayoutMain,
  //   meta: {
  //     requiresAuth: true,
  //     title: 'user',
  //   },
  //   children: [
  //     {
  //       path: "/user",
  //       component: () => import("@/views/user/index.vue"),
  //     },
  //   ],
  // })
  let xx=router.hasRoute("medicine")
  // console.log("xxxxx:",xx)

})

router.afterEach((to) => {
  const { title } = to.meta
  document.title = title ? `${title} - ${APP_NAME}` : APP_NAME
  progress.done()
})

export default router
